package com.ruoyi.apiserver.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    // 定义队列名称
    public static final String QUEUE_NAME = "mood_harbor_queue";
    
    // 定义交换机名称
    public static final String EXCHANGE_NAME = "mood_harbor_exchange";
    
    // 定义路由键
    public static final String ROUTING_KEY = "mood.harbpr.routing.key";

    /**
     * 声明队列
     * @return Queue
     */
    @Bean
    public Queue queue() {
        return new Queue(QUEUE_NAME, true); // durable: true表示持久化队列
    }

    /**
     * 声明交换机
     * @return DirectExchange
     */
    @Bean
    public DirectExchange exchange() {
        return new DirectExchange(EXCHANGE_NAME);
    }

    /**
     * 绑定队列和交换机
     * @param queue 队列
     * @param exchange 交换机
     * @return Binding
     */
    @Bean
    public Binding binding(Queue queue, DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY);
    }

    /**
     * 配置消息转换器
     * @return MessageConverter
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 配置RabbitTemplate
     * @param connectionFactory 连接工厂
     * @param messageConverter 消息转换器
     * @return RabbitTemplate
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, MessageConverter messageConverter) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(messageConverter);
        return rabbitTemplate;
    }
}